import { 
  Camera,  
  Color,  
  Mesh, 
  PlaneBufferGeometry, 
  Scene, 
  ShaderMaterial, 
  Vector3, 
  WebGLRenderer 
} from "three"

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new Camera()
camera.position.z = 1
const plane = new PlaneBufferGeometry(2, 3)

// 片元着色器
const fragmentShader = `
#include <common>

// 运行时间（以秒计）
uniform float u_time;
uniform vec3 u_color1;
uniform vec3 u_color2;

void main() {
  vec3 color = vec3(0.);

  // 颜色变化函数
  float pct = abs(sin(u_time));

  color = mix(u_color1, u_color2, pct);

  // 将 x y 映射到红色与绿色通道
  gl_FragColor = vec4(color, 1.);
}
`

// const material = new MeshBasicMaterial({ color: 'red' })
const uniforms = {
  u_time: { value: 0 },
  u_color1: { value: new Color(0xff0000) },
  u_color2: { value: new Color(0x00ff00) }
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms
})
scene.add(new Mesh(plane, material))

function render(time: number): void {
  // 转化成秒
  time *= 0.001

  uniforms.u_time.value = time

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)